package com.nhim.cms.parser;

import net.htmlparser.jericho.Segment;
import net.htmlparser.jericho.StreamedSource;
import net.htmlparser.jericho.Tag;

public class TemplateParser {
	
	static final TemplateParser INSTANCE=new TemplateParser();
	public TemplateParser()
	{
		new CMSTag().register();
	}
	public static TemplateParser getInstance()
	{
		return INSTANCE;
		
	}
	public static StringBuilder parse(String source) throws Exception
	{
		StreamedSource streamedSource=new StreamedSource(source);
		StringBuilder result = new StringBuilder();
		
		try {
			
			int lastSegmentEnd=0;
			int lastSegmentStart = 0;
			String lastSegment = "";
			
			for (Segment segment : streamedSource) {
				
				if (segment.getEnd()<=lastSegmentEnd)
				{
					
					String value = lastSegment.replace(segment.toString(), CMSHelper.processTag(segment.toString()));
					result = result.replace(lastSegmentStart, lastSegmentEnd + 2, value);
					lastSegment = value;
					continue;
				}// if this tag is inside the previous tag (e.g. a cms tag) 
				
				lastSegmentEnd=segment.getEnd();
				lastSegmentStart = result.length();
				if (segment instanceof Tag) {
					Tag tag=(Tag)segment;
					if(tag.getName().equals("$nhim"))
					{
						result.append(CMSHelper.processTag(segment.toString()) + "\n");
					}else
					{
						
						result.append(segment.toString() + "\n");
					}
					
				} else
				{
				// unless specific handling has prevented getting to here, simply output the segment as is:
					result.append(segment.toString() + "\n"  );
				}
				lastSegment = segment.toString();
			}
			
			
		}catch(Exception e)
		{
			throw e;
		}
		
		return result;
		
	}

}
